package com.itheima.practice.service;

import com.itheima.practice.tool.PackageLookupTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ChatService {

    private final ChatClient chatClient;
    private final PackageLookupTool packageTool;
    private final RuleRagService ruleRagService;
    private final Logger logger = LoggerFactory.getLogger(ChatService.class);

    // 简单内存会话存储（生产环境可用 Redis）
    private final Map<String, List<Message>> conversationMemory = new ConcurrentHashMap<>();

    public ChatService(@Qualifier("servicechatClient") ChatClient chatClient,
                       PackageLookupTool packageTool,
                       RuleRagService ruleRagService) {
        this.chatClient = chatClient;
        this.packageTool = packageTool;
        this.ruleRagService = ruleRagService;
    }

    public String chat(String sessionId, String userMessage) {
        logger.info("Session {}: User: {}", sessionId, userMessage);

        // 获取历史对话
        List<Message> history = conversationMemory.computeIfAbsent(sessionId, k -> new ArrayList<>());
        history.add(new UserMessage(userMessage));

        // 使用ChatClient的流式API直接处理
        String reply = chatClient.prompt()
                .messages(history)
                .user(userMessage)
                .call()
                .content();

        // 将回复添加到历史记录中
        history.add(new AssistantMessage(reply));

        logger.info("Session {}: AI: {}", sessionId, reply);
        return reply;
    }

    // 手动处理规则查询（可选：也可通过 Tool 实现）
    public String handleRuleQuery(String query) {
        return ruleRagService.queryRelevantRules(query);
    }
}